#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct dna_node
{
    char *dna;
    int measure;
} dna_node_t;
int measure_calculate(char *dna)
{
    int len = strlen(dna);
    int i = 0;
    int j = 0;
    int measure = 0;
    for(i = 0; i < len; i++)
    {
        for(j = i+1; j < len; j++)
        {
            if(dna[i] > dna[j])
            {
                measure++;
            }
        }
    }
    return measure;
}
int dna_node_sort(dna_node_t *arr, int len)
{
    int i = 0;
    int j = 0;
    for(i = 0; i < len-1; i++)
    {
        for(j = i+1; j < len; j++)
        {
            if(arr[i].measure > arr[j].measure)
            {
                dna_node_t tmpnode;
                memset(&tmpnode, 0, sizeof(dna_node_t));
                memcpy(&tmpnode, &arr[i], sizeof(dna_node_t));
                memcpy(&arr[i], &arr[j], sizeof(dna_node_t));
                memcpy(&arr[j], &tmpnode, sizeof(dna_node_t));
            }
        }
    }
    return 0;
}
int output_dna_node(dna_node_t *arr, int len)
{
    int i = 0;
    for(i = 0; i < len; i++)
    {
        printf("%s\n", arr[i].dna);
    }
    return 0;
}
int main()
{
    int m = 0, n = 0;
    int i = 0;
    char *s = NULL;
    dna_node_t *arr = NULL;
    scanf("%d %d", &n, &m);
    if(m <= 0 || n <= 0)
    {
        return 0;
    }
    arr = (dna_node_t *)malloc(sizeof(dna_node_t)*m);
    if(!arr)
    {
        return -1;
    }
    memset(arr, 0, sizeof(dna_node_t)*m);
    while(i < m)
    {
        arr[i].dna = (char *)malloc(n+1);
        if(!arr[i].dna)
        {
            return -1;
        }
        memset(arr[i].dna, 0, n+1);
        scanf("%s", arr[i].dna);
        arr[i].measure = measure_calculate(arr[i].dna);
        i++;
    }
    dna_node_sort(arr, m);
    output_dna_node(arr, m);
    return 0;
}
